<template>
  <div>
    <a-spin :spinning="loading">
      <a-form layout="vertical" class="operate-page-form" :model="formState" @validateFields="handleOk" ref="formRef" :rules="makeListRule">
        <div  class="operate-page-content-mo">
          <div>
          <div>
            <div class='blue-line mb-13 relative'>
              <div class="divTip1" >
                {{$t('hangManage.newGuide')}}
              </div>
              <span>{{ $t('hangManage.baseInfo') }}</span>
            </div>
            <a-row :gutter="40">
              <a-col :span="6" class="relative ">
                <a-form-item :label="`${$t('hangManage.makeNo')}:`" name="moNo">
                  <a-input :placeholder="$t('common.systemAutoGenerate')" :maxLength="20" v-model:value.trim="formState.moNo" :disabled="!showAutoSwitch" />
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item :label="`${$t('hangManage.workOrderNo')}:`" name="workOrderNo">
                  <a-input :placeholder="$t('common.pleaseInput')" v-model:value.trim="formState.workOrderNo" />
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item :label="`${$t('hangManage.preProductTime')}:`" name="productDate">
                  <a-date-picker v-model:value="formState.productDate" :showNow="false" :disabled-date="disabledStartDate" value-format="YYYY-MM-DD" />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="40">
              <a-col :span="18">
                <a-row :gutter="40">
                  <a-col :span="8" class="relative">
                    <div class="div-tip-normal" >
                      {{$t('basicData.selectStyleNo')}}
                      <div  class="point-mo"><span>1</span></div>
                    </div>
                    <a-form-item :label="`${$t('basicData.styleNo')}:`" name="styleId">
                      <a-input-group compact>
                        <div style="width: calc(100% - 34px);" :class="{'single-border': !formState.styleId}">
                          <a-select :placeholder="$t('common.pleaseSelect')" style="width: 100%;" v-model:value="formState.styleId" :options="styleList" @change="styleChange" :field-names="{ label: 'styleNo', value: 'id' }" :disabled="!showAutoSwitch">
                            <template #dropdownRender="{ menuNode: menu }">
                              <v-nodes :vnodes="menu" />
                              <a-divider class="my-4" />
                              <div class="code-link px-10" @mousedown="e => e.preventDefault()" @click="openStyle('add')">
                                <plus-outlined />
                                {{ $t('other.addStyleNo') }}
                              </div>
                            </template>
                          </a-select>
                        </div>
                        <div>
                          <a-tooltip>
                            <template #title>{{ $t('common.editor') }}</template>
                            <a-button  style="width: 32px;height:34px;" type="primary" :disabled="!formState.styleId" @click="openStyle('edit')">
                              <template #icon><FormOutlined /></template>
                            </a-button>
                          </a-tooltip>
                        </div>
                      </a-input-group>
                    </a-form-item>
                  </a-col>
                  <a-col :span="8">
                    <a-form-item :label="`${$t('basicData.styleNa')}:`" name="color">
                      <a-input v-model:value.trim="formState.styleName" :placeholder="$t('other.autoGain')" disabled />
                    </a-form-item>
                  </a-col>
                  <a-col :span="8">
                    <a-form-item :label="`${$t('basicData.productType')}:`" name="productType">
                      <a-input v-model:value.trim="formState.productType" :placeholder="$t('other.autoGain')" disabled />
                    </a-form-item>
                  </a-col>
                </a-row>
              </a-col>
            </a-row>
            <a-row :gutter="40">
              <a-col :span="18">
                <a-row :gutter="40">
                  <a-col :span="8">
                    <a-form-item :label="`${$t('basicData.color')}:`" name="colorAry">
                      <a-select :placeholder="$t('common.pleaseSelect')" v-model:value="formState.colorAry" mode="multiple" disabled>
                        <a-select-option v-for="item in colorList" :key="item.key" :value="item.code">{{item.nameCodeValue}}</a-select-option>
                      </a-select>
                    </a-form-item>
                  </a-col>
                  <a-col :span="8">
                    <a-form-item :label="`${ $t('basicData.size') }:`" name="sizeAry">
                      <a-select :placeholder="$t('common.pleaseSelect')" v-model:value="formState.sizeAry" mode="multiple" disabled>
                        <a-select-option v-for="item in sizeList" :key="item.key" :value="item.code">{{item.nameCodeValue}}</a-select-option>
                      </a-select>
                    </a-form-item>
                  </a-col>
                </a-row>
              </a-col>
            </a-row>
            <div class='blue-line mb-13 mt-10'>{{  $t('menu.basic:order')  }}</div>
            <a-row :gutter="40">
              <a-col :span="6">
                <a-form-item :label="`${$t('basicData.orderNo')}:`" name="orderId">
                  <a-select v-model:value="formState.orderId" :placeholder="$t('common.pleaseSelect')" :options="orderList" :disabled="isProd" @change="orderChange" allowClear>
                    <template #dropdownRender="{ menuNode: menu }">
                      <v-nodes :vnodes="menu" />
                      <a-divider class="my-4" />
                      <div class="code-link px-10" @mousedown="e => e.preventDefault()" @click="openOrder">
                        <plus-outlined />
                        {{ $t('other.addNewOrder') }}
                      </div>
                    </template>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item :label="`${$t('basicData.customerName')}:`" name="customId">
                  <a-select v-model:value="formState.customId" allowClear :options="customList" :placeholder="$t('common.pleaseSelect')" disabled />
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item :label="`${$t('basicData.PayDate')}:`" name="deliveryDate">
                  <a-date-picker value-format="YYYY-MM-DD" v-model:value="formState.deliveryDate" disabled />
                </a-form-item>
              </a-col>
            </a-row>
            <div>
              <MakeDetailTable ref="makeDetailTable" :tableData="detailTableData" :isProd="isProd" v-if="formState.styleId" />
            </div>
          </div>
          </div>
        </div>
        <div class="operate-page-btns">
          <a-space>
            <a-button @click="closeTab" class="cancel">{{$t('common.cancel')}}</a-button>
            <a-button @click="handleOk" type="primary" class="confirm">{{$t('common.ok')}}</a-button>
          </a-space>
        </div>

      </a-form>
      <OperateModal ref="operateModal" @ok="addOrder" />
      <OperateStyleModal ref="operateStyleModal" :isMake="true" @ok="addStyle" />
    </a-spin>
  </div>
</template>
<script setup  name="operateStaff">
import OperateStyleModal from '@/views/basicData/productInfo/designManage/modules/operateModal.vue'
import OperateModal from '@/views/basicData/orderInfo/orderManage/modules/operateModal.vue'
import MakeDetailTable from './makeDetailTable.vue'
import { ref, computed, onMounted, nextTick } from 'vue'
import { PlusOutlined, FormOutlined } from '@ant-design/icons-vue'
import { useRoute, useRouter } from 'vue-router'
import { makeListRule } from './makeConfig'
import { message } from 'ant-design-vue'
import axios from '@/utils/request'
import { cloneDeep, pick, uniqBy } from 'lodash'
import { store } from '@/store'
import { getFieldText } from '@/utils'
import moment from 'moment'
import i18n from '@/locales/index'
const { t } = i18n.global
const route = useRoute()
const router = useRouter()
let recordInfo = ref({})
let loading = ref(false)
let showAutoSwitch = ref(false)
const VNodes = (_, { attrs }) => attrs.vnodes
const operateModal = ref(null)
const operateStyleModal = ref(null)
const orderList = computed(() => {
  return store.state.normalData.orderList
})
const styleList = computed(() => {
  return store.state.normalData.styleList
})
const customList = computed(() => {
  return store.state.normalData.customList
})
const tabs = computed(() => {
  return store.state.setting.tabs
})
let colorList = ref([])
let sizeList = ref([])
let detailTableData = ref([])
let formState = ref({})
let isProd = ref(false)
const formRef = ref()
const makeDetailTable = ref()
const usedColorAry = ref([])
const usedSizeAry = ref([])


const styleChange = (value) => {
  let data = getStyleInfo(value)
  Object.assign(formState.value, data)
}
const getStyleInfo = (value) => {
  const selectStyle = value ? (styleList.value.filter(i => i.id == value)[0] || {}) : {}
  colorList.value = uniqBy((selectStyle.styleColorList || []).map(i => { return { name: i.color, code: i.colorCode, nameCodeValue: `${i.color}-${i.colorCode}` } }).concat(usedColorAry.value), 'code')
  sizeList.value = uniqBy((selectStyle.styleSizeList || []).map(i => { return { name: i.size, code: i.sizeCode, nameCodeValue: `${i.size}-${i.sizeCode}` } }).concat(usedSizeAry.value), 'code')
  nextTick(() => {
    makeDetailTable.value.onConfigAdd(colorList.value, sizeList.value)
  })
  return {
    styleId: selectStyle.id,
    styleName: selectStyle.name,
    productType: selectStyle.productType,
    colorAry: colorList.value.map(i => i.code),
    sizeAry: sizeList.value.map(i => i.code)
  }
}
const openStyle = async (type) => {
  if (type == 'add') {
    operateStyleModal.value.edit({}, false)
  } else {
    const res = await axios.getAction('/api/basic/style/get', { id: formState.value.styleId })
    if (res.success) operateStyleModal.value.edit(res.data, true, !showAutoSwitch.value)
  }
}
const addStyle = async (value) => {
  await store.dispatch('getStyle')
  styleChange(value)
}
const openOrder = () => {
  operateModal.value.initSelectOptions({
    styleList: styleList.value,
    customList: customList.value
  })
  operateModal.value.edit({})
};
const addOrder = async (id) => {
  await store.dispatch('getOrder')
  orderChange(id)
}
const orderChange = (value) => {
  let data = getOrderInfo(value)
  Object.assign(formState.value, data)
}
const getOrderInfo = (value) => {
  const selectOrder = value ? (orderList.value.filter(i => i.id == value)[0] || {}) : {}
  return {
    orderId: selectOrder.id,
    customId: selectOrder.customId,
    deliveryDate: selectOrder.deliveryDate && moment(selectOrder.deliveryDate).format('YYYY-MM-DD')
  }
}
const handleOk = async () => {
  try {
    const values = await formRef.value.validateFields()
    await makeDetailTable.value.baseForm.validateFields()
    loading.value = true
    let params = queryParams(values)
    let url = params.id ? '/api/mo/mo/edit' : '/api/mo/mo/save'
    const res = await axios.postAction(url, params)

    if (res.success) {
      message.success(res.msg || t('common.doSuccess'))
      closeTab(true)
    }
    store.dispatch('getMake')
    store.dispatch('getAllMake')
    loading.value = false
  } catch (err) {
    loading.value = false
  }
}
const closeTab = async (isSuccess) => {
  const tabList = cloneDeep(tabs.value)
  let changeTabs = tabList.filter((i) => {
    if (isSuccess) {
      return !['/makeManage/makeList', route.path].includes(i.path)
    } else {
      return i.path !== route.path
    }
  })
  await store.commit('updateState', { tabs: changeTabs })

  router.replace({ path: '/makeManage/makeList' })
}
const queryParams = (value) => {
  let params = pick(value, ['moNo', 'workOrderNo', 'styleId', 'orderId', 'productDate', 'deliveryDate'])
  let tableData = makeDetailTable.value.baseData.map(item => {
    let obj = { ...item }
    obj.color = getFieldText(colorList.value, obj.colorCode, 'code', 'name')
    obj.size = getFieldText(sizeList.value, obj.sizeCode, 'code', 'name')
    obj.id < 1 && delete obj.id
    return obj
  })
  params.moDetailList = tableData
  params.productDate = params.productDate ? moment(params.productDate).valueOf() : null
  params.deliveryDate = params.deliveryDate ? moment(params.deliveryDate).valueOf() : null
  params.id = route.fullPath.includes('copy') ? null : recordInfo.value.id
  if(route.fullPath.includes('copy')) {
     let { copy } = route.query
    params.isCopyMoProc = copy.includes('4')
    params.isCopyMoProcMapRoad = copy.includes('5')
  }
   
  styleList.value && styleList.value.forEach(i=>{
    if (i.id == params.styleId){
      params.styleNo = i.styleNo
    }
  })
  params.moNo = params.moNo? params.moNo:undefined
  return params
}
const initFormData = async () => {
  let { copy } = route.query
  let record = {}
  if (recordInfo.value.id) {
    if (route.fullPath.includes('copy')) {
      if (copy.length) {
        let ary = []
        isProd.value = false
        if (copy.includes('1')) {
          ary.push(...['workOrderNo', 'productDate', 'styleId'])
          detailTableData.value = [{ id: Math.random(), color: undefined }]
        }
        if (copy.includes('2')) ary.push('orderId')
        if (copy.includes('3')) {
          detailTableData.value = [...recordInfo.value.moDetailList]
          detailTableData.value.forEach(i => {
            i.id = Math.random()
            i.isUser = false
          })
          usedColorAry.value = recordInfo.value.moDetailColorVOList
          usedSizeAry.value = recordInfo.value.moDetailSizeVOList
        }
        record = pick(recordInfo.value, ary)
      }
    } else {
      record = { ...recordInfo.value }
      detailTableData.value = recordInfo.value.moDetailList
      usedColorAry.value = recordInfo.value.moDetailColorVOList
      usedSizeAry.value = recordInfo.value.moDetailSizeVOList
      isProd.value = record.status == 1
    }
  } else {
    recordInfo.value = {}
    detailTableData.value = [{ id: Math.random(), colorCode: undefined, sizeCode: undefined, quantity: 0 }]
  }
  record.productDate = record.productDate ? moment(record.productDate).format('YYYY-MM-DD') : recordInfo.value.id ? null : moment(new Date()).format('YYYY-MM-DD')
  record.deliveryDate = record.deliveryDate ? moment(record.deliveryDate).format('YYYY-MM-DD') : null
  await nextTick()

  formRef.value && formRef.value.resetFields()
  formState.value = cloneDeep(record)
  if (record.styleId) styleChange(record.styleId)
  if (record.orderId) orderChange(record.orderId)
}
const getDetailInfo = async (id) => {
  try {
    const res = await axios.getAction('/api/mo/mo/get', { id })
    if (res.success) recordInfo.value = res.data
  } catch {
    closeTab()
  }
}
const disabledStartDate = (current) => {
  return current && formState.value.deliveryDate && current > moment(formState.value.deliveryDate).valueOf()
}

onMounted(async () => {
  loading.value = true
  showAutoSwitch.value = route.path == '/makeManage/makeList/add' || route.path == '/makeManage/makeList/copy'
  let isNotAdd = route.fullPath !== '/makeManage/makeList/add'
  if (isNotAdd && !route.query.id) {
    closeTab()
    return
  }
  try {
    await store.dispatch('getOrder')
    await store.dispatch('getCustom')
    await store.dispatch('getStyle')
    if (route.query.id) await getDetailInfo(route.query.id)
    initFormData()
    loading.value = false
  } catch {
    loading.value = false
  }
})
</script>